package com.elitel.frame.base.controller;

import com.elitel.frame.base.service.CfgDbService;
import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.base.service.SysProjectService;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.SysProject;
import com.elitel.frame.main.entity.ext.ExtSysProject;
import com.elitel.frame.main.entity.ext.PrjServiceExt;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.PageRequestVo;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import com.elitel.frame.main.entity.vo.ZTreeDataModelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *
 * <pre>@ProjectName：frame-base-web
 * @ClassName：SysProjectController
 * @Description: TODO(工程管理配置)
 * @author：FanWenquan
 * @date：2017年11月21日 上午9:27:42
 * @version </pre>
 */
@Controller
@RequestMapping("/system/sysProject")
public class SysProjectController {
  private static final Logger logger = LoggerFactory.getLogger(SysProjectController.class);

  @Autowired private SysProjectService sysProjectService;
  @Autowired private SysPrjServiceService sysPrjServiceService;

  @Autowired
  private CfgDbService cfgDbService;

  @Value("${authorize.enable}")
  private boolean securityEnable;

  /**
   * <pre>getProjectConfigData(分页查询工程配置)
   * @author：FanWenquan
   * @date：2017年11月21日 上午10:08:55
   * @param pageNo
   * @param pageSize
   * @param seachTxt
   * @return</pre>
   */
  @RequestMapping("/getProjectConfigData")
  @ResponseBody
  public Object getProjectConfigData(String pageNo, String pageSize, String seachTxt) {
    JsonResult jr = new JsonResult();
    try {
      PageRequestVo<SysProject> pr = new PageRequestVo<SysProject>();
      pr.setSearchContent(seachTxt);
      pr.setPageNo(Integer.valueOf(pageNo));
      pr.setPageSize(Integer.valueOf(pageSize));
      PageResponseVo<SysProject> pagelist = sysProjectService.getProjectList(pr);
      jr.setData(pagelist);
      jr.setSuccess(true);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("工程配置信息加载异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * <pre>insertProjectConfig(添加工程配置)
   * @author：FanWenquan
   * @date：2017年11月21日 上午10:12:15
   * @return</pre>
   */
  @RequestMapping("/insertProjectConfig")
  @ResponseBody
  public Object insertProjectConfig(@RequestBody ExtSysProject sysProject) {
    JsonResult jr = new JsonResult();
    try {
      sysProjectService.insertProjectConfig(sysProject);
      jr.setSuccess(true);
      jr.setMsg("工程配置信息添加成功");
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg(e.getMessage());
      logger.error(e.getMessage(), e);
    }

    return jr;
  }

  /**
   * <pre>getProjectConfigByGuid(根据主键查询工程配置)
   * @author：FanWenquan
   * @date：2017年11月21日 下午12:01:37
   * @return</pre>
   */
  @RequestMapping("/getProjectConfigByGuid")
  @ResponseBody
  public Object getProjectConfigByGuid(String guid) {
    JsonResult jr = new JsonResult();
    try {
      ExtSysProject sysProject = sysProjectService.getProjectConfigByGuid(guid);
      jr.setSuccess(true);
      jr.setData(sysProject);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("获取工程配置信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }
  /**
   * <pre>updateProjectConfig(修改工程配置)
   * @author：FanWenquan
   * @date：2017年11月21日 上午10:12:31
   * @return</pre>
   */
  @RequestMapping("/updateProjectConfig")
  @ResponseBody
  public Object updateProjectConfig(@RequestBody ExtSysProject sysProject) {
    JsonResult jr = new JsonResult();
    try {
      sysProjectService.updateProjectConfig(sysProject);
      jr.setSuccess(true);
      jr.setMsg("工程配置信息修改成功");
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg(e.getMessage());
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * <pre>deleteProjectConfig(删除工程配置)
   * @author：FanWenquan
   * @date：2017年11月21日 上午10:12:40
   * @return</pre>
   */
  @RequestMapping("/deleteProjectConfig")
  @ResponseBody
  public Object deleteProjectConfig(String guids, String pcode) {
    JsonResult jr = new JsonResult();
    try {
      if (null != guids && !"".equals(guids)) {
        List<String> list = new ArrayList<String>();
        String[] idArray = guids.split(",");
        for (int i = 0; i < idArray.length; i++) {
          SysProject sysprj = sysProjectService.getProjectConfigByGuid(idArray[i]);
          List<PrjServiceExt> serverList = sysPrjServiceService.getServerByProjctId(sysprj.getPcode());
          if (null != serverList && serverList.size() > 0) {
            jr.setSuccess(false);
            jr.setMsg("请先删除服务信息！");
            break;
          }
          list.add(idArray[i]);
        }
        if (list.size() != 0 && null != list) {
          sysProjectService.deleteProjectConfig(list, pcode);
          jr.setSuccess(true);
          jr.setMsg("工程配置信息删除成功");
        }
      } else {
        jr.setSuccess(false);
        jr.setMsg("请选择要删除的工程配置信息");
      }
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("删除工程配置信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * <pre>valProjectPcode(校验工程编码)
   * @author：FanWenquan
   * @date：2017年11月21日 上午10:12:54
   * @return</pre>
   */
  @RequestMapping("/valProjectPcode")
  @ResponseBody
  public Object valProjectPcode(String pcode) {
    JsonResult jr = new JsonResult();
    try {
      List<SysProject> sysProject = sysProjectService.getProjectByPcode(pcode);
      if (null != sysProject && sysProject.size() > 0) {
        jr.setMsg("项目编码已存在,请重新输入！");
        jr.setSuccess(false);
      } else {
        jr.setSuccess(true);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      jr.setMsg("项目编码校验异常！");
      jr.setSuccess(false);
    }
    return jr;
  }

  /**
   * @Description 查询该项目是否有配置的服务
   *
   * @param pcode(项目编码)
   * @return true或false
   * @author guoyanfei
   * @date 2018/01/18
   */
  @RequestMapping("/isExitService")
  @ResponseBody
  public Boolean isExitService(HttpServletRequest request) {
    boolean result = false;
    try {
      String pcode = request.getParameter("pcode");
      List<PrjServiceExt> sysPrjservices = sysPrjServiceService.getServerByProjctId(pcode);
      if (sysPrjservices != null && sysPrjservices.size() > 0) {
        result = true;
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return result;
  }

  /**
   * 根据 pcode 获取数据源
   *
   * @param pcode
   * @return
   */
  @RequestMapping("/getProjectToDataSource")
  @ResponseBody
  public Object getProjectToDataSource(String pcode) {
    JsonResult jr = new JsonResult();
    try {
      List<CfgDb> cfgDbs = sysProjectService.selectDataSourceByProject(pcode);
      jr.setSuccess(true);
      jr.setData(cfgDbs);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("获取工程配置信息异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }

  /**
   * 根据 loginname 获取用户对应的 项目
   *
   * @param loginname
   * @return
   */
  @RequestMapping("/getProjectToUser")
  @ResponseBody
  public Object getProjectToUser(String loginname) {
    JsonResult jr = new JsonResult();
    try {
      jr.setSuccess(true);
      if (loginname == null) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        loginname = authentication.getName();
        Optional<? extends GrantedAuthority> admin =
            authentication.getAuthorities().stream()
                .filter(o -> o.getAuthority().equals("ADMIN"))
                .findFirst();
        // 如果用户是 ADMIN 则获取所有项目
        if (!securityEnable || admin.isPresent()) {
          List<ZTreeDataModelVo> list = sysProjectService.getProjectTreeList();
          jr.setData(list);
          return jr;
        }
      }

      // 根据用户 loginname 查询项目列表
      List<SysProject> sysProjects = sysProjectService.selectDataSourceByLoginName(loginname);
      jr.setData(sysProjects);
    } catch (Exception e) {
      jr.setSuccess(false);
      jr.setMsg("获取项目列表异常！");
      logger.error(e.getMessage(), e);
    }
    return jr;
  }
  // get all database config for show
  @RequestMapping("/getAllDatabase")
  @ResponseBody
  public Object getAllDatabase(){
    return cfgDbService.getAllListCfgDb();
  }


}
